package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.PermissionDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionDao permissionDao;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //取出封装数据
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage, pageSize);//分页插件，会在执行sql之前将分页关键字追加到SQL后面
        Page<Permission> page = permissionDao.findByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增权限
     *
     * @param permission
     */
    @Override
    public void add(Permission permission) {
        permissionDao.add(permission);
    }

    //根据id删除权限
    public void delete(Integer id) {
        long count = permissionDao.selectCountByPermissionId(id);
        if (count > 0) {
            //已经被关联，不能删除
            throw new RuntimeException(MessageConstant.DELETE_PERMISSION_FAIL);
        } else {
            //可以删除
            permissionDao.deleteById(id);
        }
    }

    //根据id查询权限
    public Permission findById(Integer id) {
        return permissionDao.findById(id);
    }

    public void edit(Permission permission) {
        permissionDao.edit(permission);
    }

    public List<Permission> findAll() {
        return permissionDao.findAll();
    }
}
